package cn.dzh.interceptor;


import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.alipay.sofa.runtime.api.annotation.SofaReferenceBinding;
import com.tonpower.sofarpc.facade.Authentication;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName: RequestInterceptor
 * Package: cn.dzh.interpretor
 */

@Slf4j
@Component
public class RequestInterceptor implements HandlerInterceptor{

    @SofaReference(interfaceType = Authentication.class, uniqueId = "${service.unique.id}", binding = @SofaReferenceBinding(bindingType = "bolt"))
    private Authentication authentication;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (authentication== null) {
            log.info("authentication is null");
            log.info("authentication====>{}",authentication);
            return true;
        }
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        log.info("进入拦截器====>");
        // 对请求进行拦截
        String requestURI = request.getRequestURI();
        String token = request.getHeader("Authorization"); // 获取请求头中的Token
        log.info("url====>{}",requestURI);
        log.info("token====>{}",token);
        log.info("authentication====>{}",authentication);


        Boolean allowRequest = authentication.authentication(token, requestURI);
        // 发送请求到另一个服务，并获取返回的布尔值
//        boolean allowRequest = sendRequestToAnotherService(requestURI, token);

        if (allowRequest) {
            // 如果返回的布尔值为true，放行请求
           return true;
        } else {
            // 如果返回的布尔值为false，拦截请求，可以直接返回或执行其他操作
            response.getWriter().println("Request is not allowed.");
            response.getWriter().flush();
            return false;
        }

    }




//    /**
//     * 转发请求
//     * @param path
//     * @param token
//     * @return
//     */
//    private boolean sendRequestToAnotherService(String path, String token) {
//        // 创建HttpClient对象
//        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//
//        // 更换url
//        String DNS = "http://localhost:8081";
//        String uri = DNS+"/authentication/authentication?token="+token+"&url="+path;
//        // 创建HttpGet请求，并设置请求路径和请求头（包含Token）
//        HttpGet httpGet = new HttpGet(uri);
//        httpGet.setHeader("Authorization", token);
//
//        try {
//            // 发送请求并获取响应
//            HttpResponse response = httpClient.execute(httpGet);
//
//            // 根据响应状态码判断请求是否成功，这里以200为例
//            if (response.getStatusLine().getStatusCode() == 200) {
//                // 获取响应体并转换为字符串
//                String responseBody = EntityUtils.toString(response.getEntity());
//
//                // 根据响应体内容判断返回布尔值，这里以返回"true"为例
//                if ("true".equals(responseBody)) {
//                    return true;
//                } else {
//                    return false;
//                }
//            } else {
//                // 请求失败，返回false
//                return false;
//            }
//        } catch (IOException e) {
//            // 发生异常，返回false
//            return false;
//        } finally {
//            // 关闭HttpClient连接
//            try {
//                httpClient.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }

    /**
     * 切割url
     * @param url
     * @return
     */
    public static String extractPathFromUrl(String url) {
        // 使用java.net.URL类解析URL
        java.net.URL parsedUrl;
        try {
            parsedUrl = new java.net.URL(url);
        } catch (java.net.MalformedURLException e) {
            throw new IllegalArgumentException("Invalid URL: " + url, e);
        }

        // 返回URL的路径部分
        String path = parsedUrl.getPath();
        if (path.startsWith("/")) {
            return path;
        } else {
            return "/" + path;
        }
    }
}
